package com.ly.oa.web.action;

import com.ly.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.PropertyPermission;

public class DeptDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf - 8'>");
        out.print("		<title>详情页面</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1 align='center'>部门详细信息</h1>");
        out.print("		<hr>");
        out.print("		<table border='1px' align='center' width='40%'>");

//        获取部门编号
//        /oa/dept/detail?deptno=30
//        虽然是提交的30，但服务器获取的是“30”这个字符串
        String deptno = request.getParameter("deptno");

//        连接数据库，根据部门编号查询部门信息
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "select dname,loc from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            rs = ps.executeQuery();
            if (rs.next()) {
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                out.print("			<tr>");
                out.print("				<th>部门编号</th>");
                out.print("				<td align='center'>"+deptno+"</td>");
                out.print("			</tr>");
                out.print("			<tr>");
                out.print("				<th>部门名称</th>");
                out.print("				<td align='center'>"+dname+"</td>");
                out.print("			</tr>");
                out.print("			<tr>");
                out.print("				<th>部门位置</th>");
                out.print("				<td align='center'>"+loc+"</td>");
                out.print("			</tr>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        out.print("			<tr>");
        out.print("				<td colspan='2' align='center'><input type='button' value='返回' onclick='window.history.back()'/></td>");
        out.print("			</tr>");
        out.print("		</table>");
        out.print("	</body>");
        out.print("</html>");
    }
}
